package com.cloud.common.magic_init.service;

import com.cloud.common.constants.GlobalConstants;
import com.cloud.magic_api.entity.LoginUserInfo;
import com.cloud.service.RedisService;
import com.cloud.utils.JWTUtils;
import com.cloud.utils.ToolUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisMagicService {

    @Resource
    private RedisService redisService;

    /**
     * 创建Magic 登录Token
     */
    public String createToken(LoginUserInfo userInfo) {
        String token = ToolUtils.getUuid();
        userInfo.setToken(token);
        refreshToken(userInfo);
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(GlobalConstants.tokenKey, token);
        claimsMap.put(GlobalConstants.userId, userInfo.getDeveloper().getId());
        claimsMap.put(GlobalConstants.userName, userInfo.getDeveloper().getNickName());
        return JWTUtils.createToken(claimsMap);
    }

    /**
     * 解析Token 获取Magic 登录身份信息
     *
     * @param token
     * @return
     */
    public LoginUserInfo getDeveloperUser(String token) {
        try {
            if (!token.equals("unauthorization") && StringUtils.isNotEmpty(token)) {
                String tokenKey = JWTUtils.getUserToken(token);
                return redisService.get(GlobalConstants.magicTokens + tokenKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据Token 获取Magic 身份信息
     *
     * @param magicUser
     * @return
     */
    public LoginUserInfo getDeveloperUser(MagicUser magicUser) {
        try {
            return redisService.get(GlobalConstants.magicTokens + magicUser.getToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证令牌有效期，相差不足60分钟，自动刷新缓存
     *
     * @param userInfo
     * @return 令牌
     */
    public void verifyToken(LoginUserInfo userInfo) {
        long expireTime = userInfo.getExpireTime();
        long currentTime = System.currentTimeMillis();
        long invalidTime = expireTime - currentTime;
        if (invalidTime <= GlobalConstants.MILLIS_MINUTE_TEN) {
            refreshToken(userInfo);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param userInfo 登录信息
     */
    public void refreshToken(LoginUserInfo userInfo) {
        String tokenKey = GlobalConstants.magicTokens + userInfo.getToken();
        userInfo.setLoginTime(System.currentTimeMillis());
        userInfo.setExpireTime(userInfo.getLoginTime()
                + GlobalConstants.EXPIRE_TIME * GlobalConstants.MILLIS_MINUTE);
        // 根据tokenKey将loginUser登录信息缓存
        redisService.set(tokenKey, userInfo, GlobalConstants.EXPIRE_TIME, TimeUnit.MINUTES);
    }

    /**
     * 移除Magic 登录信息
     *
     * @param token
     */
    public void removeDeveloperUser(String token) {
        try {
            if (StringUtils.isNotEmpty(token)) {
                String tokenKey = JWTUtils.getUserToken(token);
                redisService.del(GlobalConstants.magicTokens + tokenKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
